package com.cnblogs.leizia.crm.settings.service.impl;

import com.cnblogs.leizia.crm.commen.ErrorCode;
import com.cnblogs.leizia.crm.exception.LoginException;
import com.cnblogs.leizia.crm.settings.dao.UserDao;
import com.cnblogs.leizia.crm.settings.domain.User;
import com.cnblogs.leizia.crm.settings.service.UserService;
import com.cnblogs.leizia.crm.utils.DateTimeUtil;
import com.cnblogs.leizia.crm.utils.MD5Util;
import com.cnblogs.leizia.crm.utils.SqlSessionUtil;

import java.util.List;

/**
 * @author leizi
 * @create 2021-02-13 17:46
 */
public class UserServiceImpl implements UserService {

    /*
     * 由于采用静态块模式全局只有一个sqlSession,当某一线程调用时即为独占此连接，
     * 之后调用完毕session.close()(不关闭连接肯定是不行的)时就把唯一的连接关闭了，
     * 而静态块只能在每次类加载时才会重新执行。
     * 唯一的SqlSession被关闭了，且使用了被关闭的SqlSession。造成问题
     * */
//    private UserDao userDao = SqlSessionUtil.getSqlSession().getMapper(UserDao.class);

    /**
     * 用户登录
     *
     * @param loginAct 用户名
     * @param loginPwd 密码
     * @param ip
     * @return
     */
    @Override
    public User login(String loginAct, String loginPwd, String ip) throws Exception {
        // 必须每次获取自己的mapper连接，否则报：Executor was closed异常
        UserDao userDao = SqlSessionUtil.getSqlSession().getMapper(UserDao.class);
        // 查询用户信息
        User user = userDao.queryUser(loginAct);
        if (null == user) {
            throw new LoginException(ErrorCode.USER_EMPTY.getMsg());
        }
        // 校验密码是否正确
        String password = user.getLoginPwd();
        if (!loginPwd.equals(password)) {
            throw new LoginException(ErrorCode.PASSWORD_FAIL.getMsg());
        }
        // 校验ip是否允许登录
        if (!user.getAllowIps().contains(ip)) {
            throw new LoginException(ErrorCode.IP_NO_LOGIN.getMsg());
        }
        // 校验锁定状态
        if ("0".equals(user.getLockState())) {
            throw new LoginException(ErrorCode.USER_LOCK.getMsg());
        }
        // 校验失效时间
        Long timeStamp = DateTimeUtil.dateToTimeStamp(user.getExpireTime());
        if (timeStamp <= System.currentTimeMillis()) {
            throw new LoginException(ErrorCode.USER_OVERTIME.getMsg());
        }

        return user;
    }

    /**
     * 获取用户信息列表
     * @return
     */
    @Override
    public List<User> getUserList() {
        // 必须每次获取自己的mapper连接，否则报：Executor was closed异常
        UserDao userDao = SqlSessionUtil.getSqlSession().getMapper(UserDao.class);
        List<User> userList = userDao.getUserList();

        return userList;
    }
}
